import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { PhotoLibrary } from '@ionic-native/photo-library';
import { Toast } from '@ionic-native/toast';

declare var $: any

@Component({
  selector: 'page-album',
  templateUrl: 'album.html'
})
export class AlbumPage {
  private zancun_imgs: any = []
  private select_imgs: any = []
  private remaining_imgs: any = []
  private database: any
  private isCanEdit: any = false;
  constructor(public navCtrl: NavController,
    private navParams: NavParams,
    private photoLibrary: PhotoLibrary,
    private toast: Toast) {
    this.zancun_imgs = this.navParams.data.zancun_album_imgs;
    this.database = this.navParams.data.database;

  }

  goback() {
    this.navCtrl.pop()
  }
  ionViewDidEnter() {
    this.zancun_imgs.forEach(element => {
      element.selected = false;
      console.log(element.selected);
    });
    console.log('album zancun_imgs')
    console.log(this.zancun_imgs)
  }
  ionViewWillEnter() {
    this.getNode();
  }
  getNode() {
    let parentNode = document.getElementById("container");
    let childNodeArray: any = parentNode.getElementsByClassName("box");
    let screenWidth = document.documentElement.clientWidth;
    let childWidth = childNodeArray[0].offsetWidth;
    let num = Math.floor(screenWidth / childWidth); //获得一排摆的个数 用Math.floor()转换为整数
    parentNode.style.cssText = "width:" + childWidth * num + "px; margin:0 auto"; //固定container的宽并设置居中
    this.setImagePosition(num, childNodeArray);
  }

  setImagePosition(num, childArray) {
    var imgHeightArray = [];//定义数组用于存放所有图片的高度
    for (var i = 0; i < childArray.length; i++) { //遍历所有图片
      if (i < num) {
        imgHeightArray[i] = childArray[i].offsetHeight; //取得第一排图片的高度
      } else {
        var minHeight = Math.min.apply(null, imgHeightArray); //获取第一排图片中高度最小的图片
        var minIndex = this.getMinHeight(imgHeightArray, minHeight); //函数获得高度最小的图片的位置
        childArray[i].style.position = "absolute"; //绝对定位图片
        childArray[i].style.top = minHeight + "px"; //图片距顶部像素
        childArray[i].style.left = childArray[minIndex].offsetLeft + "px"; //图片距左的像素
        imgHeightArray[minIndex] = imgHeightArray[minIndex] + childArray[i].offsetHeight; //将最低高度的box的高度加上它下方的box高度
      }
    }
  }

  getMinHeight(imgHeightArray, minHeight) {
    for (var i in imgHeightArray) {
      if (imgHeightArray[i] == minHeight) { //循环所有数组的高度 让它等于最小图片的高度 返回i值
        return i;
      }
    }
  }


  onEdit() {
    this.isCanEdit = true;
  }
  onCancel() {
    this.isCanEdit = false;
  }

  onSelect(id) {
    this.zancun_imgs.forEach(element => {
      if (element.id === id) {
        element.selected = !element.selected;
      }
    });
  }

  getSelected_img() {
    this.select_imgs = [];
    this.remaining_imgs = [];
    this.zancun_imgs.forEach(element => {
      if (element.selected == true) {
        this.select_imgs.push(element);
      } else {
        this.remaining_imgs.push(element);
      }
    });
  }

  delete() {
    this.getSelected_img();
    if (this.select_imgs.length == 0) {
      this.toast.show('请选择需删除的图片。', '3000', 'center').subscribe();
    } else {
      this.select_imgs.forEach(element => {
        this.database.executeSql("DELETE FROM kj_imgs WHERE id=?;", [element.id])
          .then(() => {
            this.toast.show('删除成功', '3000', 'center').subscribe();
          })
          .catch(e => console.log(e));//删除数据
      });
      this.zancun_imgs = this.remaining_imgs;
      this.isCanEdit = false;
      this.getNode();
    }
  }

  down() {
    this.getSelected_img();
    if (this.select_imgs.length == 0) {
      this.toast.show('请选择需要保存的图片。', '3000', 'center').subscribe();
    } else {
      this.photoLibrary.requestAuthorization().then(() => {
        this.photoLibrary.getLibrary().subscribe({
          next: () => {
            this.select_imgs.forEach(element => {
              this.photoLibrary.saveImage(element.dataUrl, "KuaiJian")
            });
          },
          error: err => { alert(err) },
          complete: () => {
            this.toast.show('保存到相册。', '3000', 'center').subscribe();
            this.isCanEdit = false;
          }
        })
      }).catch(err => console.log('permissions weren\'t granted'));
    }
  }

}
